<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

interface MonthlyStats {
  [key: string]: number
}

interface ReasonStats {
  reason: string
  count: number
}

interface DepartmentStats {
  department: number
  count: number
}

const scrapApi = {
  getMonthlyStats: () => {
    return request<MonthlyStats>({
      method: 'GET',
      url: '/scrap/stats/monthlyCount'
    })
  },
  
  getReasonStats: () => {
    return request<ReasonStats[]>({
      method: 'GET',
      url: '/scrap/stats/reasonRatio'
    })
  },
  
  getDepartmentStats: () => {
    return request<DepartmentStats[]>({
      method: 'GET',
      url: '/scrap/stats/byDepartment'
    })
  }
}

const monthlyChartRef = ref<HTMLElement | null>(null)
const reasonChartRef = ref<HTMLElement | null>(null)
const departmentChartRef = ref<HTMLElement | null>(null)

const getMonthlyStats = async () => {
  try {
    const response = await scrapApi.getMonthlyStats()
    initMonthlyChart(response.data)
  } catch (error) {
    ElMessage.error('获取月度统计失败')
    console.error(error)
  }
}

const getReasonStats = async () => {
  try {
    const response = await scrapApi.getReasonStats()
    initReasonChart(response.data)
  } catch (error) {
    ElMessage.error('获取原因统计失败')
    console.error(error)
  }
}

const getDepartmentStats = async () => {
  try {
    const response = await scrapApi.getDepartmentStats()
    initDepartmentChart(response.data)
  } catch (error) {
    ElMessage.error('获取部门统计失败')
    console.error(error)
  }
}

const initMonthlyChart = (data: MonthlyStats) => {
  if (!monthlyChartRef.value) return
  
  const chart = echarts.init(monthlyChartRef.value)
  const months = Object.keys(data).sort()
  const counts = months.map(month => data[month])
  
  const option = {
    backgroundColor: 'rgba(240, 248, 240, 0.9)', // 淡绿色背景
    title: {
      text: '月度报废申请趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#2c3e50'
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(44, 62, 80, 0.8)',
      textStyle: { color: '#fff' },
      formatter: '{b}<br/>数量: {c}',
      padding: 10,
      extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLine: {
        lineStyle: {
          color: '#bdc3c7'
        }
      },
      axisLabel: {
        color: '#7f8c8d',
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(189, 195, 199, 0.3)'
        }
      },
      axisLabel: {
        color: '#7f8c8d'
      }
    },
    series: [{
      data: counts,
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 10,
      showSymbol: false,
      hoverAnimation: true,
      itemStyle: {
        color: '#3498db',
        borderWidth: 2,
        borderColor: '#fff'
      },
      lineStyle: {
        width: 4,
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          { offset: 0, color: '#3498db' },
          { offset: 1, color: '#2980b9' }
        ]),
        shadowColor: 'rgba(0, 0, 0, 0.3)',
        shadowBlur: 10,
        shadowOffsetY: 5
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(52, 152, 219, 0.4)' },
          { offset: 1, color: 'rgba(52, 152, 219, 0.05)' }
        ])
      },
      emphasis: {
        focus: 'series',
        scale: true
      }
    }]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
  
  chart.on('mouseover', (params) => {
    if (params.componentType === 'series') {
      chart.setOption({
        series: [{
          showSymbol: true
        }]
      })
    }
  })
  
  chart.on('mouseout', (params) => {
    if (params.componentType === 'series') {
      chart.setOption({
        series: [{
          showSymbol: false
        }]
      })
    }
  })
}

const initReasonChart = (data: ReasonStats[]) => {
  if (!reasonChartRef.value) return
  
  const chart = echarts.init(reasonChartRef.value)
  // const total = data.reduce((sum, item) => sum + item.count, 0)
  
  const option = {
    backgroundColor: 'rgba(240, 248, 240, 0.9)', // 淡绿色背景
    title: {
      text: '报废原因占比',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#2c3e50'
      }
    },
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(44, 62, 80, 0.8)',
      textStyle: { color: '#fff' },
      formatter: '{b}: {c} ({d}%)',
      padding: 10,
      extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: data.map(item => item.reason),
      textStyle: {
        color: '#7f8c8d'
      },
      itemWidth: 12,
      itemHeight: 12,
      borderRadius: 6
    },
    series: [
      {
        name: '报废原因',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: () => {
          return Math.random() * 200 + 200
        },
        itemStyle: {
          borderRadius: 6,
          borderColor: '#fff',
          borderWidth: 2,
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.2)'
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b|{b}}\n{per|{d}%}',
          rich: {
            b: {
              fontSize: 12,
              fontWeight: 'bold',
              color: '#2c3e50'
            },
            per: {
              color: '#7f8c8d',
              backgroundColor: '#f0f8f0', // 淡绿色背景
              padding: [2, 4],
              borderRadius: 2
            }
          }
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 20,
          lineStyle: {
            color: '#bdc3c7'
          }
        },
        data: data.map(item => ({
          value: item.count,
          name: item.reason,
          itemStyle: {
            color: getColorByIndex(data.indexOf(item))
          }
        }))
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const initDepartmentChart = (data: DepartmentStats[]) => {
  if (!departmentChartRef.value) return
  
  const chart = echarts.init(departmentChartRef.value)
  
  // 按数量降序排序
  const sortedData = [...data].sort((a, b) => b.count - a.count)
  const departments = sortedData.map(item => `部门 ${item.department}`)
  const counts = sortedData.map(item => item.count)
  
  const option = {
    backgroundColor: 'rgba(240, 248, 240, 0.9)', // 淡绿色背景
    title: {
      text: '部门报废数量TOP5',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#2c3e50'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      backgroundColor: 'rgba(44, 62, 80, 0.8)',
      textStyle: { color: '#fff' },
      formatter: '{b}<br/>数量: {c}',
      padding: 10,
      extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(189, 195, 199, 0.3)'
        }
      },
      axisLabel: {
        color: '#7f8c8d'
      }
    },
    yAxis: {
      type: 'category',
      data: departments,
      axisLine: {
        lineStyle: {
          color: '#bdc3c7'
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#7f8c8d',
        padding: [0, 10, 0, 0]
      }
    },
    series: [
      {
        name: '报废数量',
        type: 'bar',
        data: counts,
        animationDuration: 1500,
        animationEasing: 'elasticOut',
        itemStyle: {
          color: (params: any) => {
            const colorList = [
              '#e74c3c', '#e67e22', '#f1c40f', '#2ecc71', '#3498db'
            ]
            return colorList[params.dataIndex % colorList.length]
          },
          borderRadius: [4, 0, 0, 4],
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.2)'
        },
        barWidth: '60%',
        label: {
          show: true,
          position: 'right',
          formatter: '{c}',
          color: '#2c3e50',
          fontWeight: 'bold',
          fontSize: 12
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 20,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const getColorByIndex = (index: number): string => {
  // 丰富的非绿色系配色
  const colors = [
    '#e74c3c', '#3498db', '#9b59b6', '#e67e22', '#f1c40f',
    '#1abc9c', '#34495e', '#d35400', '#8e44ad', '#2980b9',
    '#f39c12', '#c0392b', '#7f8c8d', '#16a085', '#27ae60'
  ]
  return colors[index % colors.length]
}

onMounted(() => {
  getMonthlyStats()
  getReasonStats()
  getDepartmentStats()
})
</script>

<template>
  <el-card class="card-box">
    <div class="header">
      <h2>报废统计分析</h2>
    </div>
    
    <div class="chart-container">
      <div class="chart-row">
        <div class="chart-item">
          <div ref="monthlyChartRef" class="chart"></div>
        </div>
        <div class="chart-item">
          <div ref="reasonChartRef" class="chart"></div>
        </div>
      </div>
      <div class="chart-row">
        <div class="chart-item full-width">
          <div ref="departmentChartRef" class="chart"></div>
        </div>
      </div>
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.card-box {
  width: 100%;
  max-width: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  padding: 0;
  overflow: hidden;
}

.header {
  padding: 0.8rem 1.2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e6eaf0;
  background-color: #f7f9fc;
  
  h2 {
    font-weight: 600;
    font-size: 1.4rem;
    color: #333;
    user-select: none;
    margin: 0;
  }
}

.chart-container {
  padding: 1rem;
}

.chart-row {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
  
  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.chart-item {
  flex: 1;
  height: 300px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  }
  
  &.full-width {
    flex: 0 0 100%;
  }
}

.chart {
  width: 100%;
  height: 100%;
}
</style>